# -*- coding: utf-8 -*-

import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urlencode, datetime
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanLiangshanlizuPolicy(BaseTaxPolicySpider):
    name = 'sichuan_liangshanlizu_qu_policy'

    province = '四川省'
    city = '凉山彝族自治州'
    # county = '滑县'
    park = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['彝族自治州德昌县人民政府', "德昌县", "http://www.lsdc.gov.cn/zfxxgk_85/zc/newgfxwj/index.html"],
            ['彝族自治州德昌县人民政府', "德昌县", "http://www.lsdc.gov.cn/zfxxgk_85/zc/xzfwjnew/"],
            ['彝族自治州德昌县人民政府', "德昌县", "http://www.lsdc.gov.cn/zfxxgk_85/zc/xzfbgswjnew/"],
            ['彝族自治州普格县人民政府', "普格县", "http://www.pgx.gov.cn/zfxxgk/zfxxgknr/zcwj_30921/gfxwj1/"],
            ['彝族自治州普格县人民政府', "普格县", "http://www.pgx.gov.cn/zfxxgk/zfxxgknr/zcwj_30921/xzfwjnew/"],
            ['彝族自治州普格县人民政府', "普格县", "http://www.pgx.gov.cn/zfxxgk/zfxxgknr/zcwj_30921/xzfbgswjnew/"],
            ['彝族自治州金阳县人民政府', "金阳县", "http://www.jinyang.gov.cn/zfxxgk_31494/zfxxgknr/zcwj/gfxwj_1/index.html"],
            ['彝族自治州金阳县人民政府', "金阳县", "http://www.jinyang.gov.cn/zfxxgk_31494/zfxxgknr/zcwj/zcxwj/"],
            ['彝族自治州金阳县人民政府', "金阳县", "http://www.jinyang.gov.cn/zfxxgk_31494/zfxxgknr/zcwj/xzfwj_1/"],
            ['彝族自治州金阳县人民政府', "金阳县", "http://www.jinyang.gov.cn/zfxxgk_31494/zfxxgknr/zcwj/xzfbgswj_1/"],
            ['彝族自治州盐源县人民政府', "盐源县", "http://www.yanyuan.gov.cn/zfxxgk/zfxxgknr/zcwj_31049/gfxwj/index.html"],
            ['彝族自治州盐源县人民政府', "盐源县", "http://www.yanyuan.gov.cn/zfxxgk/zfxxgknr/zcwj_31049/xzfwj1/"],
            ['彝族自治州盐源县人民政府', "盐源县", "http://www.yanyuan.gov.cn/zfxxgk/zfxxgknr/zcwj_31049/xzfbgswj1/"],
        ]:
            item = {'source': source, 'county': county}
            if 'index.' not in url:
                url += 'index.html'
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            # "//div[@class='gknr_list']//li[@class='hui']//a[(contains(@href, 'shtml') and @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=5] | "
            "//ul[contains(@class, 'list') or contains(@id, 'list')]//li//a[(contains(@href, 'html') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=5]"
        )

        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])

            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if 'htm' not in item['source_url']:
                continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath("""string(.)""").re_first(r"""createPageHTML\((\d+)""") or 0
            print(response.url, 'total', total_page)
            for page_num in range(1, int(total_page)):
                yield response.follow(re.sub(r"index\.", r"index_{}.".format(page_num), response.url), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get() or response.xpath("/title/text()").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").re_first(r"\d{4}-\d{2}-\d{2}")
        print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_liangshanlizu_qu_policy".split())
